package com.haoting.usercenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haoting.commonutils.CommonResult;
import com.haoting.commonutils.JwtUtils;
import com.haoting.usercenter.client.OssClient;
import com.haoting.usercenter.entity.Consumer;
import com.haoting.usercenter.entity.vo.ConsumerQuery;
import com.haoting.usercenter.entity.vo.LoginVo;
import com.haoting.usercenter.entity.vo.RegisterVo;
import com.haoting.usercenter.service.ConsumerService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tingting
 * @since 2021-01-08
 */
@RestController
@RequestMapping("/usercenter/consumer")
//@CrossOrigin
public class ConsumerController {
    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private OssClient ossClient;


    //用户注册
    @PostMapping("register")
    public CommonResult registerUser(@RequestBody RegisterVo registerVo){
        String token = consumerService.register(registerVo);
        return CommonResult.ok().data("token",token);
    }

    //用户登录
    @PostMapping("login")
    public CommonResult login(@RequestBody LoginVo loginVo){
        String token = consumerService.login(loginVo);

        return CommonResult.ok().data("token",token);
    }
    //判断用户名是否存在
    @GetMapping("isusername/{username}")
    public CommonResult isusername(@PathVariable String username){
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        int count = consumerService.count(wrapper);
        if(count>=1){
            return CommonResult.ok().data("exist","true");
        }else {
            return CommonResult.error().data("exist","false");
        }
    }
    //判断手机号是否存在
    @GetMapping("isphone/{mobile}")
    public CommonResult isphone(@PathVariable String mobile){
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        int count = consumerService.count(wrapper);
        if(count>=1){
            return CommonResult.ok().data("exist","true");
        }else {
            return CommonResult.error().data("exist","false");
        }
    }

    //根据token获取用户信息
    @GetMapping("getMemberInfo")
    public CommonResult getMemberInfo(HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        return CommonResult.ok().data("userInfo",consumerService.getById(memberId));
    }


    @ApiOperation(value = "所有用户列表")
    @GetMapping("/findAll")
    public CommonResult findAll(){
        List<Consumer> list = consumerService.list(null);
        return CommonResult.ok().data("items",list);
    }

    @ApiOperation(value = "所有作者列表")
    @GetMapping("/findAllauthor")
    public CommonResult findAllauthor(){
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
        wrapper.eq("role","2")
                .or()
                .eq("role","0");

        List<Consumer> list = consumerService.list(wrapper);
        return CommonResult.ok().data("items",list);
    }
    @ApiOperation(value = "逻辑删除用户")
    @DeleteMapping("{id}")
    public CommonResult removeUser(@ApiParam(name = "id",value="用户ID",required = true)@PathVariable String id){

        Consumer consumer = consumerService.getById(id);
        String imagename[] = consumer.getAvatar().split("/");
        String name = imagename[3]+"/"+imagename[4];
        ossClient.deleteOssfile(imagename[3],imagename[4]);


        boolean flag = consumerService.removeById(id);
        if(flag){
            return CommonResult.ok().data("name",name);
        }else {
            return CommonResult.error();
        }

    }

    @ApiOperation(value = "分页查询用户列表")
    @GetMapping("/pageUsers/{current}/{limit}")
    public CommonResult pageListUser(@PathVariable long current,@PathVariable long limit){
        Page<Consumer> pageUser = new Page<>(current,limit);
        consumerService.page(pageUser,null);
        long total = pageUser.getTotal();//总记录数
        List<Consumer> records = pageUser.getRecords();//数据list集合
        return CommonResult.ok().data("total",total).data("rows",records);
    }

    @ApiOperation(value = "分页条件查询用户列表")
    @PostMapping("pageUserCondition/{current}/{limit}")
    public CommonResult pageUserCondition(@PathVariable long current, @PathVariable long limit,
                                          @RequestBody(required = false) ConsumerQuery consumerQuery){
        Page<Consumer> pageUser = new Page<>(current,limit);
        //多条件组合查询
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
        String name = consumerQuery.getName();
        String role = consumerQuery.getRole();
        String begin = consumerQuery.getBegin();
        String end = consumerQuery.getEnd();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("username",name);//传的是表中字段名称
        }
        if(!StringUtils.isEmpty(role)){
            if(role.equals("2")){
                wrapper.eq("role","2")
                        .or()
                        .eq("role","0");
            }else{
                wrapper.eq("role",role);
            }

        }
        if(!StringUtils.isEmpty(begin)){
            wrapper.ge("created",begin);
        }
        if(!StringUtils.isEmpty(end)){
            wrapper.le("created",end);
        }

        //排序
        wrapper.orderByDesc("created");
        consumerService.page(pageUser,wrapper);
        long total = pageUser.getTotal();
        List<Consumer> records = pageUser.getRecords();
        return CommonResult.ok().data("total",total).data("rows",records);
    }


    @ApiOperation(value = "添加用户")
    @PostMapping("addUser")
    public CommonResult addUser(@RequestBody Consumer consumer){
        boolean save = consumerService.save(consumer);
        if(save){
            return CommonResult.ok();
        }else {
            return CommonResult.error();
        }
    }

    @ApiOperation(value = "根据id进行查询")
    @GetMapping("getUser/{id}")
    public CommonResult getUser(@PathVariable String id){
        Consumer consumer = consumerService.getById(id);
        return CommonResult.ok().data("consumer",consumer);
    }

    @ApiOperation(value = "用户修改")
    @PostMapping("updateConsumer")
    public CommonResult updateConsumer(@RequestBody Consumer consumer){
        boolean save = consumerService.updateById(consumer);
        if(save){
            return CommonResult.ok();
        }else {return CommonResult.error();}
    }



}

